<template>
  <div class="meeting-signin">
    <div class="title">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;会议签到</div>
    <div class="content">
      <a-form :model="formQuery">
        <a-form-item label="启用会议签到：">
          <a-switch v-model="formQuery.enableSignOut" checked-value="1" unchecked-value="0" />
        </a-form-item>

        <template v-if="formQuery.enableSignOut === '1'">
          <a-form-item label="允许签到时间：">
            <div class="input-group">
              <div class="input-wrapper">
                会议开始前
                <a-input-number
                  v-model="signInBeforeMinutesNum"
                  :style="{ width: '6vw' }"
                  placeholder=""
                  class="input-demo"
                  :min="0"
                  :max="60"
                />
                分钟可以签到
              </div>
              <div class="sign-in-tip">会议开始后15分钟结束签到</div>
            </div>
          </a-form-item>

          <a-form-item label="允许签退时间：">
            <div class="input-group">
              <div class="input-wrapper">
                <span class="label">会议签到结束</span>
                <a-input
                  v-model:model-value="formQuery.signOutMinutesAfterSignIn"
                  :style="{ width: '5vw' }"
                  placeholder=""
                  allow-clear
                />
                <span class="label">分钟后才能签退</span>
              </div>
              <div class="input-wrapper">
                <span class="label">会议结束</span>
                <a-input
                  v-model:model-value="formQuery.signOutAfterEndMinutes"
                  :style="{ width: '5vw' }"
                  placeholder=""
                  allow-clear
                />
                <span class="label">分钟后不能签退</span>
              </div>
            </div>
          </a-form-item>
        </template>

        <a-form-item label="门口屏背景设置：">
          <div class="update-method-wrapper">
            <a-radio-group v-model="formQuery.updateMethod">
              <a-radio value="restoreDefault">恢复默认图片</a-radio>
              <a-radio value="single">自定义图片</a-radio>
              <a-radio value="">不更新</a-radio>
            </a-radio-group>
          </div>
          <div v-if="formQuery.updateMethod === 'single'" class="upload-container">
            <a-form-item>
              <template v-if="!formQuery.backgroundImageURL">
                <div class="upload-wrapper">
                  <input
                    ref="fileInputRef"
                    type="file"
                    accept="image/jpeg,image/png,image/jpg"
                    class="file-input"
                    @change="handleImageUpload"
                  />
                  <div class="upload-btn">
                    <icon-plus />
                    <div class="upload-text">上传图片</div>
                  </div>
                </div>
              </template>
              <template v-else>
                <div class="preview-container">
                  <a-image
                    :src="formQuery.backgroundImageURL"
                    :preview="true"
                    title="背景图片"
                    class="preview-image"
                  />
                  <div class="image-actions">
                    <a-button type="primary" status="danger" size="mini" @click="removeImage">
                      <template #icon><icon-delete /></template>
                    </a-button>
                  </div>
                </div>
              </template>
            </a-form-item>
            <div class="upload-tip">
              <a-typography-text type="secondary">
                请上传小于2M，分辨率1280*800大小的图片，以获得最佳显示效果。
              </a-typography-text>
            </div>
          </div>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue'
import { Message } from '@arco-design/web-vue'
import axios from 'axios'

const _props = defineProps<{
  meetingId: string
}>()
// 使用defineEmits注册一个自定义事件
const emit = defineEmits(['meeting-signin-fc'])

const _file = ref<null>(null)
const _fileList = ref<any[]>([])

interface SignInForm {
  backgroundImageURL: string
  signInBeforeMinutes: string
  enableSignOut: string
  signOutMinutesAfterSignIn: string
  signOutAfterEndMinutes: string
  updateMethod: string
}

const formQuery = ref<SignInForm>({
  backgroundImageURL: '',
  signInBeforeMinutes: '0',
  enableSignOut: '0',
  signOutMinutesAfterSignIn: '',
  signOutAfterEndMinutes: '',
  updateMethod: ''
})

const fileInputRef = ref<HTMLInputElement | null>(null)

const signInBeforeMinutesNum = computed({
  get: () => Number(formQuery.value.signInBeforeMinutes),
  set: (val: number) => {
    formQuery.value.signInBeforeMinutes = String(val)
  }
})

// 提交前处理数据
const processDataBeforeSubmit = () => {
  const data = { ...formQuery.value }

  // 如果启用签到，确保其他签到相关字段有值
  if (data.enableSignOut === '1') {
    data.signInBeforeMinutes = data.signInBeforeMinutes || '15'
    data.signOutMinutesAfterSignIn = data.signOutMinutesAfterSignIn || '15'
    data.signOutAfterEndMinutes = data.signOutAfterEndMinutes || '30'
  }

  return data
}

// 处理图片上传
const handleImageUpload = (event: Event) => {
  const input = event.target as HTMLInputElement
  const file = input.files?.[0]

  if (!file) {
    Message.error('请选择图片')
    return
  }

  // 检查文件大小（2MB限制）
  if (file.size > 2 * 1024 * 1024) {
    Message.error('图片大小不能超过2MB')
    return
  }

  const formData = new FormData()
  formData.append('file', file)

  // 获取token
  const token = localStorage.getItem('token') || sessionStorage.getItem('token') || ''

  // 显示上传中提示
  const loadingMsg = Message.loading({
    content: '正在上传...',
    duration: 0
  })

  // 使用axios上传
  axios.post('/user/file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data',
      'Authorization': `Bearer ${token}`
    }
  })
    .then((response) => {
      // 关闭loading提示
      loadingMsg.close()

      // 兼容后端返回code为0、'0'、200、'200'都视为成功
      if (response.data.code === 200 || response.data.code === '200' || response.data.code === 0 || response.data.code === '0') {
        formQuery.value.backgroundImageURL = response.data.data
        Message.success('上传成功')
      } else {
        Message.error(response.data.msg || '上传失败')
      }
    })
    .catch((error) => {
      loadingMsg.close()
      Message.error(`上传失败：${error.message || '未知错误'}`)
    })

  // 重置input，允许重复上传相同文件
  if (fileInputRef.value) {
    fileInputRef.value.value = ''
  }
}

// 移除图片
const removeImage = () => {
  formQuery.value.backgroundImageURL = ''
  if (fileInputRef.value) {
    fileInputRef.value.value = ''
  }
}

// 监听变化并发送数据
watch(formQuery, (_newVal) => {
  emit('meeting-signin-fc', processDataBeforeSubmit())
}, { deep: true })

// 新增：监听启用签到开关，自动设置默认值
watch(() => formQuery.value.enableSignOut, (val) => {
  if (val === '1') {
    if (!formQuery.value.signInBeforeMinutes || formQuery.value.signInBeforeMinutes === '0') formQuery.value.signInBeforeMinutes = '15'
    if (!formQuery.value.signOutMinutesAfterSignIn) formQuery.value.signOutMinutesAfterSignIn = '15'
    if (!formQuery.value.signOutAfterEndMinutes) formQuery.value.signOutAfterEndMinutes = '15'
  }
})

// 组件挂载时发送初始数据，并初始化默认值
onMounted(() => {
  if (formQuery.value.enableSignOut === '1') {
    if (!formQuery.value.signInBeforeMinutes || formQuery.value.signInBeforeMinutes === '0') formQuery.value.signInBeforeMinutes = '15'
    if (!formQuery.value.signOutMinutesAfterSignIn) formQuery.value.signOutMinutesAfterSignIn = '15'
    if (!formQuery.value.signOutAfterEndMinutes) formQuery.value.signOutAfterEndMinutes = '15'
  }
  emit('meeting-signin-fc', processDataBeforeSubmit())
})
</script>

<style lang="scss" scoped>
.meeting-signin {
  .title {
    font-size: 16px;
    font-weight: 500;
    margin-bottom: 20px;
  }

  .content {
    .input-group {
      display: flex;
      flex-direction: column;
      gap: 12px;

      .input-wrapper {
        display: flex;
        align-items: center;
        gap: 8px;

        .label {
          white-space: nowrap;
        }
      }

      .sign-in-tip {
        color: var(--color-text-3);
        font-size: 13px;
        margin-left: 2px;
      }

      .help-icon {
        color: var(--color-text-3);
        cursor: help;
      }
    }

    .update-method-wrapper {
      margin-bottom: 16px;
    }

    .upload-container {
      margin-top: 12px;

      .upload-tip {
        margin-top: 8px;
        font-size: 12px;
      }

      .upload-wrapper {
        position: relative;
        width: 100px;
        height: 100px;
        border: 1px dashed var(--color-border-2);
        border-radius: 2px;
        cursor: pointer;
        transition: border-color 0.3s;

        &:hover {
          border-color: var(--color-primary);
        }

        .file-input {
          position: absolute;
          width: 100%;
          height: 100%;
          opacity: 0;
          cursor: pointer;
          z-index: 2;
        }

        .upload-btn {
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          width: 100%;
          height: 100%;
          color: var(--color-text-3);

          .upload-text {
            margin-top: 8px;
            font-size: 14px;
          }
        }
      }

      .preview-container {
        position: relative;
        width: 100px;
        height: 100px;
        overflow: hidden;
        border: 1px solid var(--color-border-2);
        border-radius: 2px;

        .preview-image {
          width: 100%;
          height: 100%;
          object-fit: contain;
          background: #f7f7f7;
          cursor: pointer;
        }

        .image-actions {
          position: absolute;
          top: 0;
          right: 0;
          display: none;
          padding: 4px;
          border-radius: 0 0 0 4px;
          background-color: rgba(0, 0, 0, 0.5);
        }

        &:hover .image-actions {
          display: block;
        }
      }
    }
  }
}
</style>
